﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.ComponentModel; 
 

// GetTPB, Copyright Mirosław M. Mączka.  All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
namespace GetTpb
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        BackgroundWorker bw = new BackgroundWorker();
        int nAllChildren = 0;
        int nCheckedChildren = 0;
        private double progressStep = 0.1;
        private TpbSource[] ts;
        private bool [] boxChecked;
        public MainWindow()
        {
            InitializeComponent();
            //
            TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal;
            //
            bw.WorkerReportsProgress = true;
            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.ProgressChanged +=new ProgressChangedEventHandler(bw_ProgressChanged);
            bw.RunWorkerCompleted +=new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            showVersion();
            //
            ConfigTextFile ctf = new ConfigTextFile();
            ctf.ReadOrCreate();

            foreach (TpbSource s in ctf)
            {
                CheckBox ckb = new CheckBox();
                ckb.IsThreeState = false;
                //ckb.Content = s.Title;
                ckb.ToolTip = s.Title;
                ckb.Tag = s;
                ckb.IsChecked = true;
                ckb.Margin = new Thickness(15.0, 15.0, 15.0, 15.0);
                TextBlock tb = new TextBlock();
                tb.Text = s.Title;
                tb.ToolTip = s.Title;
                ckb.Content = tb;
                //
                wrapPanel1.Children.Add(ckb);
            }
        }

        //private void CheckBox_ItemSelectionChanged(object sender,  CheckBoxItemSelectionChangedEventArgs e)
        //{
            //if (!button1.IsEnabled)
            //{
                //if (e.IsSelected) e.Item.Selected = false;
            //}

        //}

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            button1.IsEnabled = false;
            //wrapPanel1.IsEnabled = false;
            //
            nAllChildren = wrapPanel1.Children.Count;
            ts = new TpbSource[nAllChildren];
            boxChecked = new bool[nAllChildren];
            nCheckedChildren = 0;
            for(int i=0; i< nAllChildren; i++)
            {
                if ((bool)((CheckBox)wrapPanel1.Children[i]).IsChecked)
                {
                    nCheckedChildren++;
                    ts[i] = (TpbSource)((CheckBox)wrapPanel1.Children[i]).Tag; ;
                    boxChecked[i] = true;
                    ((TextBlock)((CheckBox)wrapPanel1.Children[i]).Content).Background = Brushes.Yellow;
                }
                //((CheckBox)wrapPanel1.Children[i]).IsEnabled = false;
            }
            //
            if (nCheckedChildren > 0)
            {
                double progressStep = 1.0 / nCheckedChildren;
            }
            else this.Close();
            //
            bw.RunWorkerAsync();
            //
        }

        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            //
            if (nCheckedChildren > 0)
            {
                //
                Parallel.For(0, nAllChildren, i =>
                {
                    if (!boxChecked[i]) goto skip;
                    //
                    bool isOK = doWork(ts[i], i);
                    worker.ReportProgress(isOK?1:0, (object)i);
                skip: ;
                });
                //
            }

        }

        private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int n = (int)e.UserState;
            ((CheckBox)wrapPanel1.Children[n]).IsChecked = false;
            ((TextBlock)((CheckBox)wrapPanel1.Children[n]).Content).Background = 0 != e.ProgressPercentage ? Brushes.PaleGreen: Brushes.Coral;
            TaskbarItemInfo.ProgressValue += progressStep;
        }

        private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TaskbarItemInfo.ProgressValue = 1.0;
            System.Threading.Thread.Sleep(500);
            this.Close();
        }



        private bool doWork(TpbSource ts, int nCheckBox)
        {
            HashSet<TpbItem> hs = new HashSet<TpbItem>();
            string ErrorMessage="";
            int nPages;
            bool isOK = true;
            try
            {
                isOK = ReadAllPages.Do(hs, ts, out nPages, out ErrorMessage);
                //
                //
                if (!isOK)
                {
                    File.WriteAllText(ts.Title + ".htm", TpbUtils.Error2String(ts.Title, ErrorMessage));
                }
                else
                {
                    string s = TpbUtils.HashSet2String(ts.Title, hs);
                    //
                    try
                    {
                        File.WriteAllText(ts.Title + ".htm", s);
                    }
                    catch (Exception e1)
                    {
                        File.WriteAllText(ts.Title + ".htm", TpbUtils.Error2String(ts.Title, e1.Message));
                        isOK = false;
                    }
                }
            }
            catch
            {
                isOK = false;
            }
            //
            return isOK;
        }

        private void MenuItem_Select_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < wrapPanel1.Children.Count; i++)
            {
                ((CheckBox)wrapPanel1.Children[i]).IsChecked = true;
            }
        }

        private void MenuItem_Unselect_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < wrapPanel1.Children.Count; i++)
            {
                ((CheckBox)wrapPanel1.Children[i]).IsChecked = false;
            }
        }

        private void showVersion()
        {
            string version = "";
            if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)//ClickOnce
            {
                version = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion.ToString();
            }
            else
            {
                version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            }
            window1.Title = String.Format("{0} ({1})", window1.Title, version);
        }

    }
}

